import { defineStore } from 'pinia'
import { getStorage, setStorage, removeStorage } from '@/utils/db'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    rankings: []
  }),
  
  getters: {
    isLoggedIn(state) {
      return !!state.userInfo
    },
    userRank(state) {
      if (!state.userInfo) return -1
      return state.rankings.findIndex(r => r.userId === state.userInfo.id) + 1
    }
  },
  
  actions: {
    // 初始化用户状态
    initUserState() {
      const savedUser = getStorage('currentUser')
      if (savedUser) {
        this.userInfo = savedUser
      }
      
      const savedRankings = getStorage('rankings')
      if (savedRankings) {
        this.rankings = savedRankings
      }
    },
    
    // 用户登录
    async login(username, password) {
      const users = getStorage('users') || []
      const user = users.find(u => u.username === username && u.password === password)
      console.log(users)
      console.log(user)
      if (user) {
        this.userInfo = user
        setStorage('currentUser', user)
        return true
      }
      
      return false
    },
    
    // 用户注册
    async register(username, password) {
      const users = getStorage('users') || []
      
      // 检查用户名是否已存在
      if (users.some(u => u.username === username)) {
        return { success: false, message: '用户名已存在' }
      }
      
      // 验证格式
      if (username.length < 2 || username.length > 8) {
        return { success: false, message: '用户名长度必须为2-8个字符' }
      }
      
      if (password.length < 6 || password.length > 16) {
        return { success: false, message: '密码长度必须为6-16个字符' }
      }
      
      // 创建新用户
      const newUser = {
        id: Date.now().toString(),
        username,
        password,
        createdAt: new Date().toISOString()
      }
      
      users.push(newUser)
      setStorage('users', users)
      
      // 初始化排名
      const rankings = getStorage('rankings') || []
      rankings.push({
        userId: newUser.id,
        username: newUser.username,
        score: 0,
        updatedAt: new Date().toISOString()
      })
      
      setStorage('rankings', rankings)
      this.rankings = rankings
      
      return { success: true, user: newUser }
    },
    
    // 用户登出
    logout() {
      this.userInfo = null
      removeStorage('currentUser')
    },
    
    // 更新用户积分
    updateUserScore(score) {
      if (!this.userInfo) return
      
      let userRanking = this.rankings.find(r => r.userId === this.userInfo.id)
      
      if (userRanking) {
        userRanking.score = score
        userRanking.updatedAt = new Date().toISOString()
      } else {
        this.rankings.push({
          userId: this.userInfo.id,
          username: this.userInfo.username,
          score: score,
          updatedAt: new Date().toISOString()
        })
      }
      
      // 排序并保存
      this.rankings.sort((a, b) => b.score - a.score)
      setStorage('rankings', this.rankings)
    }
  }
})